package club.zhilin.guli.service.ucenter.service.impl;

import club.zhilin.guli.common.base.domain.JwtInfo;
import club.zhilin.guli.common.base.result.CommonResult;
import club.zhilin.guli.common.base.result.CommonResultCodeEnum;
import club.zhilin.guli.common.base.util.JwtUtil;
import club.zhilin.guli.service.base.dto.MemberDTO;
import club.zhilin.guli.service.base.exception.GlobalException;
import club.zhilin.guli.service.ucenter.domain.Member;
import club.zhilin.guli.service.ucenter.domain.vo.LoginVO;
import club.zhilin.guli.service.ucenter.domain.vo.RegisterVO;
import club.zhilin.guli.service.ucenter.mapper.MemberMapper;
import club.zhilin.guli.service.ucenter.service.IMemberService;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Date;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author zhilin
 * @since 2022-02-24 17:34:48
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {

    private final RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public CommonResult<String> register(RegisterVO registerVO) {
        if (StringUtils.isEmpty(registerVO.getMobile()) || !PhoneUtil.isMobile(registerVO.getMobile())) {
            return CommonResult.failed(CommonResultCodeEnum.PARAM_ERROR);
        }
        // 判断参数
        if (StringUtils.isEmpty(registerVO.getNickname()) || StringUtils.isEmpty(registerVO.getPassword()) || StringUtils.isEmpty(registerVO.getCode())) {
            return CommonResult.failed(CommonResultCodeEnum.PARAM_ERROR);
        }
        // 用户验证码是否正确
        String code = (String) redisTemplate.opsForValue().get(registerVO.getMobile());
        if (!registerVO.getCode().equals(code)) {
            return CommonResult.failed(CommonResultCodeEnum.CODE_ERROR);
        }
        // 用户是否被注册
        Long count = baseMapper.selectCount(new LambdaQueryWrapper<Member>().eq(Member::getMobile, registerVO.getMobile()).or().eq(Member::getMobile, registerVO.getMobile()));
        if (count > 0) {
            return CommonResult.failed(CommonResultCodeEnum.REGISTER_USER_ERROR);
        }
        // 注册
        Member member = new Member();
        BeanUtils.copyProperties(registerVO, member);
        member.setPassword(SecureUtil.md5(member.getPassword()));
        member.setAvatar("https://guli-college-files-oss.oss-cn-beijing.aliyuncs.com/avatar/2022/02/14/069eaac6-be6f-4553-a10b-cc453425eae4.jpg");
        member.setDisabled(false);
        baseMapper.insert(member);
        return CommonResult.success("保存成功");
    }

    @Override
    public CommonResult<String> login(LoginVO loginVO) {
        // 校验参数是否合法
        if (StringUtils.isEmpty(loginVO.getMobile()) || !PhoneUtil.isMobile(loginVO.getMobile()) || StringUtils.isEmpty(loginVO.getPassword())) {
            return CommonResult.failed(CommonResultCodeEnum.PARAM_ERROR);
        }
        // 校验手机号是否存在
        Member member = baseMapper.selectOne(new LambdaQueryWrapper<Member>().eq(Member::getMobile, loginVO.getMobile()));
        if (member == null) {
            return CommonResult.failed(CommonResultCodeEnum.LOGIN_MOBILE_ERROR);
        }
        // 校验密码是否正确
        if (!SecureUtil.md5(loginVO.getPassword()).equals(member.getPassword())) {
            return CommonResult.failed(CommonResultCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 检擦用户是否被禁用
        if (Boolean.TRUE.equals(member.getDisabled())) {
            return CommonResult.failed(CommonResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        member.setLastLogin(new Date());
        // 更新登录时间
        this.updateById(member);
        JwtInfo jwtInfo = new JwtInfo(member.getId(), member.getNickname(), member.getAvatar());
        String token = JwtUtil.createJwtToken(jwtInfo, 1800);
        return CommonResult.success("登录成功", token);
    }

    @Override
    public Member getByOpenId(String openId) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Member>().eq(Member::getOpenid, openId));
    }

    @Override
    public CommonResult<MemberDTO> selectMember(String memberId) {
        Member member = baseMapper.selectOne(new LambdaQueryWrapper<Member>().eq(Member::getId, memberId));
        if (member == null) {
            throw new GlobalException(CommonResultCodeEnum.PARAM_ERROR);
        }
        MemberDTO memberDTO = new MemberDTO();
        BeanUtils.copyProperties(member, memberDTO);
        return CommonResult.success(memberDTO);
    }

    @Override
    public Integer selectRegisterCount(String date) {
        return baseMapper.selectRegisterCount(date);
    }

    @Override
    public Integer selectLoginCount(String date) {
        return baseMapper.selectLoginCount(date);
    }
}
